let http = require("http");
let fs = require("fs");
let url = require("url");
let path = require("path")

let sliders = require("./sliders.js");

const pageSize = 5;

function read(cb) {
    fs.readFile(path.resolve("mock/books.json"), "utf8", function(error, data) {
        console.log(error);

        if (error || data.length == 0) {
            cb([]);
        } else {
            cb(JSON.parse(data))
        }
    })
}


function writer(data, cb) {
    fs.writeFile(path.resolve("mock/books.json"), JSON.stringify(data), cb)
}



http.createServer((req, res) => {
    let { pathname, query } = url.parse(req.url, true);

    res.setHeader("Access-Control-Allow-Origin", "*");
    res.setHeader("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
    res.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.setHeader("X-Powered-By", ' 3.2.1')
    if (req.method == "OPTIONS") return res.end(); /*让options请求快速返回*/

    if (pathname === "/sliders") {
        res.setHeader('Content-Type', "application/json;chartset='utf8'");
        res.end(JSON.stringify(sliders));
    }


    if (pathname === "/hot") {
        read(function(books) {
            let hot = books.reverse().slice(0, 6);
            res.setHeader('Content-Type', "application/json;chartset='utf8'");
            setTimeout(() => {
                res.end(JSON.stringify(hot))
            }, 1000);
        })
    }

    if (pathname === "/book") {
        let id = parseInt(query.id);
        switch (req.method) {
            case 'GET':
                if (!isNaN(id)) {
                    read((books) => {
                        let book = books.find(item => item.bookId == id);
                        if (!book) book = {}
                        res.setHeader('Content-Type', "application/json;chartset='utf8'");
                        res.end(JSON.stringify(book))
                    })
                } else {
                    read(function(books) {
                        res.setHeader('Content-Type', "application/json;chartset='utf8'");
                        res.end(JSON.stringify(books.reverse()))
                    });
                }
                break;
            case 'POST':
                let str = "";
                req.on("data", chunk => {
                    str += chunk;
                });
                req.on("end", () => {
                    let book = JSON.parse(str);
                    read((books) => {
                        book.bookId = books.length ? books[books.length - 1].bookId + 1 : 1;
                        books.push(book);
                        writer(books, () => {
                            res.end(JSON.stringify(book));
                        })
                    })

                })

                break;
            case 'PUT':
                if (id) {
                    let str = '';
                    req.on('data', chunk => {
                        str += chunk;
                    });

                    req.on('end', () => {
                        let book = JSON.parse(str);
                        console.log("book的值", book);
                        read(function(books) {
                            books = books.map(item => {

                                console.log("bookId=" + item.bookId);
                                console.log("id=" + id);

                                if (item.bookId === id) {
                                    return book;
                                }
                                return item;
                            });

                            console.log("books的值：", books)
                            writer(books, () => {
                                res.end(JSON.stringify(book))
                            })
                        })
                    })
                }
                break;
            case 'DELETE':
                read((books) => {
                    books = books.filter(item => item.bookId !== id);
                    writer(books, () => {
                        res.end(JSON.stringify({}))
                    })
                })


                break;
        }
        return;
    }
    if (pathname === "/page") {

        let offset = parseInt(query.offset) || 0;
        read(books => {
            books = books.slice(offset, offset + pageSize);
            res.setHeader('Content-Type', "application/json;chartset='utf8'");
            res.end(JSON.stringify(books))
        })
    }

}).listen(3000);